package com.snopy.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author snopy
 * @version 1.0.0
 * @classname UDPServer
 * @description
 * @email 77912204@qq.com
 * @date 2022/06/11 1:00
 */
@Slf4j
public class UDPServer {
    public static void main(String[] args) throws IOException {


        try {
            DatagramSocket serverSocket = new DatagramSocket(8021);
            while (true) {
                System.out.println("正在监听------");
                byte[] bytes = new byte[1024];
                DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
                serverSocket.receive(dp);
                log.info("----接收消息:{}----", Arrays.toString(dp.getData()));
                //UDPServiceThread thread1 = new UDPServiceThread(socket);
                //thread1.start();
            }
        }catch (Exception e){

        }



    }

}
class UDPServiceThread extends Thread {
    private Socket socket;


    public UDPServiceThread(Socket t_socket) {
        socket = t_socket;
    }

    @Override
    public void run() {
        System.out.println("线程开始，打印该客户端的ip和端口");
        System.out.println(socket.getLocalAddress() + ": " + socket.getLocalPort());
        InputStream clientInput = null;
        InputStreamReader clientInputStream = null;
        BufferedReader clientBufferReader = null;
        OutputStream clientOutStream = null;
        Writer clientWriter = null;
        System.out.println("打印该客户端的请求报文头");
        try {
            clientBufferReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String st = null;
            while ((st = clientBufferReader.readLine()) != null && st.length() != 0) {
                System.out.println(st);

                //System.out.println(st.substring(st.indexOf(":")));
            }

            socket.shutdownInput();
            //System.out.println("构造回应报文头并发送给还客户端");
            clientWriter = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
            clientWriter.write("HTTP/1.2 200 \r\n");
            //clientWriter.write("Transfer-Encoding: chunked\r\n");

            clientWriter.write("Content-Type: text/html;charset=UTF-8\r\n");
            clientWriter.write("\r\n");

            clientWriter.write("Hello\r\n");
            clientWriter.write("World\r\n");
            clientWriter.flush();
            socket.close();

        } catch (Exception e) {

        }
    }
}